package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.bean.Category;
import org.example.exception.*;
import org.example.mapper.CategoryMapper;
import org.example.service.CategoryService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public JsonResult findCategory() {
        return ResultTool.success(list());
    }

    @Override
    public JsonResult findCategory(int page) {
        //之前确认分页信息 page：页码：10：每页显示多少条
        Page<Category> p = Page.of(page, 10);
        List<Category> list = list(p);
        p.setRecords(list);
        return ResultTool.success(p);
    }
    @Override
    public JsonResult findCategoryById(String id){
        Category one = getById(id);
        return ResultTool.success(one);
    }
    @Override
    public JsonResult findCategoryByname(String name,int page){
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.like("name",name);
        Page<Category> of = Page.of(page, 10);
        List<Category> list = list(of, wrapper);
        of.setRecords(list);
        return ResultTool.success(of);
    }
    @Override
    public JsonResult saveCategory(Category category){
        boolean save=save(category);
        if (!save){
            throw new UserSaveException("添加分类失败");
        }
        return ResultTool.success("success");
    }
        @Override
    public JsonResult updateCategory(Category user){
        boolean update=updateById(user);
            if (!update){
                throw new UserSaveException("更新用户失败");
            }
            return ResultTool.success("success");
    }
    @Override
    public JsonResult removeCategory(String id){
        boolean remove=removeById(id);
        if (!remove){
            throw new UserSaveException("删除用户失败");
        }
        return ResultTool.success("success");
    }
    @Override
    public JsonResult updateCategoryStatus(String id,int status){
        UpdateWrapper<Category> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id);
        wrapper.set("status",status);
        boolean update=update(wrapper);
        if (!update){
            throw new UserRemoveException("修改状态失败");
        }
        return ResultTool.success("success");
    }
}
